<template>
  <div class="applicationDetail">
    <div class="title-box"><span>应用包管理</span><span class="back return" @click="goback">&lt;&nbsp;返回</span></div>
    <div class="details">
      <div class="title">应用包&nbsp;{{ details.data.name }}&nbsp;详情</div>
      <el-form ref="table" :model="modifyDetails.data" :rules="rules">
        <div class="details-card">
          <div class="content-box" v-for="(item, key) in basic" :key="key">
            <div class="content-label">{{ item }}</div>
            <div :class="key == 'description' || key == 'build_state_reason' ? 'content-text-description' : 'content-text'">
              <div v-if="key == 'description'">
                <div v-if="descriptionFlag">
                  <el-form-item :prop="key">
                    <el-input v-model="modifyDetails.data[key]" type="textarea" :rows="2" maxlength="1024" show-word-limit></el-input
                  ></el-form-item>
                </div>
                <div v-else class="creation">{{ details.data[key] ? details.data[key] : '--' }}</div>
              </div>
              <div v-else-if="key == 'name'">
                <div v-if="nameFlag">
                  <el-form-item :prop="key"> <el-input v-model="modifyDetails.data[key]" maxlength="50" minlength="2" /></el-form-item>
                </div>
                <div v-else class="creation">{{ details.data[key] ? details.data[key] : '--' }}</div>
              </div>
              <div v-else-if="key == 'version'">
                <div v-if="versionFlag">
                  <el-form-item :prop="key"> <el-input v-model="modifyDetails.data[key]" maxlength="50" /></el-form-item>
                </div>
                <div v-else class="creation">{{ details.data[key] ? details.data[key] : '--' }}</div>
              </div>
              <div v-else-if="key == 'size'">{{ details.data[key] ? details.data[key] : '--' }}<span v-if="details.data[key] != '--'">&nbsp;Mb</span></div>
              <div v-else class="content-text">{{ details.data[key] ? details.data[key] : '--' }}</div>
              <div v-if="key == 'description'">
                <div v-if="descriptionFlag"><span class="modify" @click="confirm(0)">确定</span><span class="modify cancel" @click="cancel(0)">取消</span></div>
                <div v-else><span class="modify mod" @click="change(0)" v-if="userType >= 5">修改</span></div>
              </div>
              <div v-else-if="key == 'name'">
                <div v-if="nameFlag"><span class="modify" @click="confirm(1)">确定</span><span class="modify cancel" @click="cancel(1)">取消</span></div>
                <div v-else><span class="modify" @click="change(1)" v-if="userType >= 5">修改</span></div>
              </div>
              <div v-else-if="key == 'version'">
                <div v-if="versionFlag"><span class="modify" @click="confirm(2)">确定</span><span class="modify cancel" @click="cancel(2)">取消</span></div>
                <div v-else><span class="modify" @click="change(2)" v-if="userType >= 5">修改</span></div>
              </div>
            </div>
          </div>
        </div>
        <el-divider />
        <div class="details-card">
          <div class="content-box" v-for="(item, key) in time" :key="key">
            <div class="content-label">{{ item }}</div>
            <div class="content-text" v-if="details.data[key]">{{ details.data[key] }}</div>
            <div class="content-text" v-else>--</div>
          </div>
        </div>
        <el-divider />
        <div class="details-card">
          <div class="content-box" v-for="(item, key) in image" :key="key">
            <div class="content-label">{{ item }}</div>
            <div class="content-text" v-if="key == 'image_region'">{{ details.data[key] ? $t(details.data[key]) : '--' }}</div>
            <div class="content-text" v-else>{{ details.data[key] ? details.data[key] : '--' }}</div>
          </div>
        </div>
        <el-divider />
        <div class="details-card">
          <div class="content-box" v-for="(item, key) in obs" :key="key">
            <div class="content-label">{{ item }}</div>
            <div class="content-text" v-if="key == 'storage_region'">{{ details.data[key] ? $t(details.data[key]) : '--' }}</div>
            <div class="content-text" v-else>{{ details.data[key] ? details.data[key] : '--' }}</div>
          </div>
        </div>
        <el-divider />
        <div class="details-card">
          <div class="content-box" v-for="(item, key) in users" :key="key">
            <div class="content-label">{{ item }}</div>
            <div class="content-text" v-if="key == 'user'">{{ details.data[key] ? $t(details.data[key]) : '--' }}</div>
            <div class="content-text" v-else>{{ details.data[key] ? details.data[key] : '--' }}</div>
          </div>
        </div>
      </el-form>
    </div>
    <div class="details">
      <div class="title">已关联Fleet</div>
      <div class="app-table">
        <el-table
          :data="tableData"
          style="width: 100%"
          :header-cell-style="{ background: '#f4f5f8', color: '#252b3a' }"
          :border="true"
          :default-sort="{ prop: 'creation_time', order: 'descending' }"
        >
          <el-table-column label="Fleet名称" width="200">
            <template #default="scope">
              <div class="toDetails" @click="toFleet(scope.row.fleet_id, scope.row.fleet_name)">
                {{ scope.row.fleet_name }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="fleet_id" label="FleetID" />
          <el-table-column label="状态">
            <template #default="scope">
              {{ scope.row.fleet_state ? $t(scope.row.fleet_state) : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="creation_time" label="创建时间" :formatter="timeFormatUTC" sortable />
        </el-table>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
  @import '@/assets/scss/dropdownBox.scss';
  .applicationDetail {
    .title-box {
      span {
        font-size: 16px;
        font-weight: bold;
        margin-left: 20px;
        margin-right: 21px;
        line-height: 60px;
      }
      .return {
        margin-left: -11px;
        font-size: 14px;
      }
    }

    .details {
      .details-card {
        margin: -10px 0 -10px 0;
        .content-box {
          .content-text {
            .creation {
              width: auto;
              word-break: break-all;
            }
            .el-form-item {
              margin-bottom: 0;
            }
          }
          .content-text-description {
            width: 550px;
            word-break: break-all;
            font-size: 14px;
            color: #252b3a;
            display: flex;
            align-items: center;
            .creation {
              width: auto;
              word-break: break-all;
            }
            .mod {
              display: flex;
              white-space: nowrap;
            }
            .el-form-item {
              margin-bottom: 0;
            }
          }
          .modify {
            margin-left: 20px;
            font-size: 14px;
            color: #325cb0;
            cursor: pointer;
          }
          .cancel {
            margin-left: 10px;
          }
          .el-input {
            width: 420px;
            height: 30px;
          }
          .el-textarea {
            width: 450px;
            word-break: break-all;
          }
        }
      }
    }
    .details:last-of-type {
      margin-top: 20px;
    }
    .app-table {
      :deep(.el-table) {
        border-radius: 2px;
        font-size: 14px;
        color: $text-color;
        tr {
          border-color: $border-color;
          height: 78px;
        }
        thead > tr:first-child {
          height: 36px;
        }
        .el-table__cell {
          border-right: none;
        }
      }
      :deep(.toDetails) {
        color: $main-color;
        cursor: pointer;
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      :deep(.toDetails:hover) {
        text-decoration: underline;
      }
      :deep(.id-box) {
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      :deep(.cell) {
        padding: 0 30px 0 20px;
      }
    }
  }
</style>
<script lang="ts" setup>
  import appStore from '@/store'
  import { timeFormatUTC } from '@/utils/formatter'
  import { reactive, ref } from 'vue'
  import router from '@/router'
  import { useRoute } from 'vue-router'
  import ApplicationService, { App, updateApp } from '@/api/applicationService'
  import { timeFormathmsUTC } from '@/utils/formatter'
  import { ElMessage, FormInstance, FormRules } from 'element-plus'
  const basic = {
    id: 'ID',
    name: '应用包名',
    size: '应用包大小',
    build_type: '应用包类型',
    version: '版本号',
    state: '状态',
    build_state_reason: '状态原因',
    operating_system: '操作系统',
    description: '描述'
  }

  const time = {
    creation_time: '创建时间',
    update_time: '更新时间'
  }

  const image = {
    image_id: '镜像ID',
    image_region: '镜像区域'
  }
  const users = {
    user: '使用用户',
    group: '所属用户组'
  }
  const obs = {
    storage_bucket_name: '对象桶名',
    storage_key: '存储对象名',
    storage_region: '存储区域'
  }

  const state: { [key: string]: string } = {
    INITIALIZED: '初始化',
    READY: '就绪',
    FAILED: '创建失败',
    IMAGE_CREATING: '镜像创建中'
  }
  const route = useRoute()
  let nameFlag = ref(false)
  let versionFlag = ref(false)
  let descriptionFlag = ref(false)
  let userType = ref()
  userType.value = localStorage.getItem('UserType') as string
  let buildApp: App = {
    project_id: appStore.userStore.project_id,
    build_id: `${route.params.id}`
  }
  const table = ref<FormInstance>()
  let tableData: Array<{ [key: string]: string }> = reactive([])
  let submitApp: updateApp = {
    project_id: appStore.userStore.project_id,
    build_id: `${route.params.id}`,
    UpdateBuildRequestBody: {
      name: '',
      description: '',
      version: ''
    }
  }
  const rules = reactive<FormRules>({
    name: [
      { required: true, message: '请输入应用包名称', trigger: 'blur' },
      { min: 2, message: '名称长度应在2-50范围内', trigger: 'blur' },
      {
        pattern: /^[A-Za-z][\dA-Za-z\_\-]{1,49}$/,
        message: '以英文字母开头，并由英文字母、数字或“_”、“-”组成',
        trigger: 'blur'
      }
    ],
    version: [{ required: true, message: '请输入版本号', trigger: 'blur' }]
  })
  let details: { [key: string]: { [key: string]: string } } = reactive({ data: {} })
  let modifyDetails: { [key: string]: { [key: string]: string } } = reactive({ data: {} })
  const toDetails = async () => {
    let res = await ApplicationService.getApplicationDetail(buildApp)
    if (res.status === 200) {
      details.data = res.data.build
      modifyDetails.data.name = details.data.name
      modifyDetails.data.version = details.data.version
      modifyDetails.data.description = details.data.description
      details.data.update_time = timeFormathmsUTC(details.data.update_time)
      details.data.creation_time = timeFormathmsUTC(details.data.creation_time)
      details.data.state = state[details.data.state]
      details.data.size = res.data.build.size != 0 ? (res.data.build.size / 1024 / 1024).toFixed(2) : '--'
      tableData.length = 0
      if (res.data.fleet_list.fleet) {
        tableData.push(...res.data.fleet_list.fleet)
      }
    }
  }

  const goback = () => {
    router.push({
      name: 'applicationList'
    })
  }

  const change = (i: Number) => {
    if (i == 0) {
      modifyDetails.data.description = details.data.description
      descriptionFlag.value = true
    } else if (i == 1) {
      modifyDetails.data.name = details.data.name
      nameFlag.value = true
    } else {
      modifyDetails.data.version = details.data.version
      versionFlag.value = true
    }
  }

  const cancel = (i: Number) => {
    if (i == 0) {
      descriptionFlag.value = false
    } else if (i == 1) {
      nameFlag.value = false
    } else {
      versionFlag.value = false
    }
  }

  const confirm = async (i: Number) => {
    submitApp.UpdateBuildRequestBody = {
      name: modifyDetails.data.name,
      description: modifyDetails.data.description,
      version: modifyDetails.data.version
    }
    let formValid: any
    if (i == 0) {
      submitApp.UpdateBuildRequestBody.description = modifyDetails.data.description
    } else if (i == 1) {
      formValid = await table.value?.validateField('name', (valid) => {
        return valid
      })
      if (!formValid) {
        return
      }
      submitApp.UpdateBuildRequestBody.name = modifyDetails.data.name
    } else {
      formValid = await table.value?.validateField('version', (valid) => {
        return valid
      })
      if (!formValid) {
        return
      }
      submitApp.UpdateBuildRequestBody.version = modifyDetails.data.version
    }

    let res = await ApplicationService.modifyApplication(submitApp)
    if (res.status === 200) {
      cancel(i)
      if (i == 0) {
        details.data.description = modifyDetails.data.description
      } else if (i == 1) {
        details.data.name = modifyDetails.data.name
      } else {
        details.data.version = modifyDetails.data.version
      }
    }
  }
  const toFleet = (id: string, name: string) => {
    router.push({ name: 'fleetDetails', params: { id, name } })
  }

  toDetails()
</script>
